const api = require('../../utils/api');

Page({
  data: {
    currentTab: 0,
    orders: [],
    tabs: ['全部', '待付款', '待取餐', '已完成']
  },
  onLoad: function() {
    this.loadOrders();
  },
  onShow: function() {
    this.loadOrders();
  },
  switchTab: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentTab: index
    });
    this.loadOrders();
  },
  loadOrders: async function() {
    // 本地模拟：读取storage
    const allOrders = wx.getStorageSync('orders') || [];
    let orders = allOrders;
    
    // 根据currentTab过滤订单
    if (this.data.currentTab > 0) {
      orders = allOrders.filter(order => order.status === this.data.currentTab - 1);
    }
    
    this.setData({ orders });
  },
  cancelOrder: async function(e) {
    const orderId = e.currentTarget.dataset.id;
    try {
      await wx.showModal({
        title: '提示',
        content: '确定要取消该订单吗？'
      });
      
      wx.showLoading({ title: '处理中' });
      await api.updateOrder(orderId, { status: 4 }); // 4表示已取消
      
      wx.showToast({
        title: '订单已取消',
        icon: 'success'
      });
      
      this.loadOrders();
    } catch (error) {
      if (error.errMsg !== 'showModal:cancel') {
        wx.showToast({
          title: '取消失败',
          icon: 'error'
        });
      }
    } finally {
      wx.hideLoading();
    }
  },
  payOrder: async function(e) {
    const orderId = e.currentTarget.dataset.id;
    try {
      wx.showLoading({ title: '处理中' });
      await api.updateOrder(orderId, { status: 1 }); // 1表示待取餐
      
      wx.showToast({
        title: '支付成功',
        icon: 'success'
      });
      
      this.loadOrders();
    } catch (error) {
      wx.showToast({
        title: '支付失败',
        icon: 'error'
      });
    } finally {
      wx.hideLoading();
    }
  },
  onPullDownRefresh: function() {
    this.loadOrders().then(() => {
      wx.stopPullDownRefresh();
    });
  }
}); 